var count = 0;
var list_url = "./zone/list.do?type=json";
var rm_url = "./zone/rm.do?ajax=true&id=";
$(function(){
    fetch(list_url, {credentials: "same-origin"})
        .then(function(response){
            return response.json();
        })
        .then(function(weibos){
            builder(weibos);
        })
        .then(function() {
			$('#list-weibo li button').on('click', function() {
				var $self = $(this);
				fetch(rm_url + $self.data('id'), {credentials: "same-origin"})
					.then(function(response) {
						return response.json();
					})
					.then(function(obj) {
						if(obj.ok === 1) {
							$self.parent('li').remove();
							document.getElementById("weiboCount").innerHTML --;
						}
					})
					.catch(function(err) {
						alert(err);
					})
			})
		})
		.catch(function(){
			window.location.href='/favebook/signin.jsp';
		})
})

$(document).ready(function(){  
    var range = 100;                     
    var flag = 1; 
    var flagPoin = 2;
    var maxFlag = 100;
    var totalheight = 0;   
	    $(window).scroll(function(){  
	        var srollPos = $(window).scrollTop();  
	        totalheight = parseFloat($(window).height()) + parseFloat(srollPos); 
//	        console.log("滚动条到顶部的垂直高度: "+$(document).scrollTop()); 
//	        console.log("页面的文档高度 ："+$(document).height());  
//	        console.log('浏览器的高度：'+$(window).height());
//	        console.log(srollPos);
	        if(($(document).height()- range) <= totalheight && flag <= maxFlag) {
	        	fetch(list_url + "&page=" + flag, {credentials: "same-origin"})
			        .then(function(response){
		                return response.json();
		            })
		            .then(function(weibos){
		            	builder(weibos);
		            	maxFlag = parseInt(count / 10);
	            	})
				flag ++;
	        	flagPoin = flag;
	        } 
	    })  
})

function builder(weibos){
	var $ul = $("#list-weibo");
    var info = weibos.pop();
    weibos.forEach(function(web) {
    	if(info.currentUserName === web.username) {
            $ul.append(
                '<li class="panel panel-style">' +
                '<h4>' + web.username + '</h4>' +
                '<h6>' + web.publishDate + '</h6>' +
                '<p>' + web.content + '</p>' +
                '<button data-id="' + web.id + '">删除</button>' +
                '</li>'
            )
        }
    	document.getElementById("userName").innerHTML = info.currentUserName;
    	document.getElementById("userEmail").innerHTML = info.currentUserEmail;
    	document.getElementById("weiboCount").innerHTML = info.weiboPerCount;
    	count = info.weiboCount;
    })
}
